package api_day09;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class FileDemo {
    @Test //创建文件单元
    public void test1() throws IOException {
        File file1 = new File("src/a.txt");
        File file2 = new File("src/a");
        File file3 = new File("src/a/b.txt");
        boolean b1 = file1.createNewFile();
        boolean b2 = file2.mkdir();
        boolean b3 = file3.createNewFile();
        System.out.println(b1 + " " + b2 + " " + b3 + " ");
    }
    @Test //获取文件路径单元
    public void test2(){
        //方式1
        //方式2
        String path2 = FileDemo.class.getResource("").getPath();
        System.out.println(path2);
        //方式3
        String path3 = FileDemo.class.getClassLoader().getResource("a/b.txt").getPath();
        System.out.println(path3);
    }
    @Test //判断、删除文件方法
    public void test3(){
        File file1 = new File("src/a.txt");
        File file2 = new File("src/a");
        File file3 = new File("src/a/b.txt");
        boolean is1 = file1.isFile();
        boolean is2 = file1.isDirectory();
        boolean is3 = file2.isFile();
        boolean is4 = file2.isDirectory();
        System.out.println(is1 + " " + is2 + " " + is3 + " "+ is4);
        test4(file2);
        /*boolean d1 = file1.delete();
        System.out.print(d1 + " ");
        boolean d2 = file2.delete();
        System.out.print(d2 + " ");
        boolean d3 = file3.delete();
        System.out.print(d3 + " ");
        boolean d4 = file2.delete();
        System.out.print(d4 + " ");*/
    }
    //递归方法删除文件及其子文件
    public void test4(File file){
        File[] files = file.listFiles();
        //非空文件才递归，否则直接删除
        if (files != null){
            for (File f : files){
                if (f.isFile()) f.delete();
                if (f.isDirectory()) test4(f);
            }
        }

        file.delete();
    }
}
